package org.jeecg.modules.wlhy.hydriverbank.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.ArrayListDict;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainDriver;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainVehicle;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainDriverService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainVehicleService;
import org.jeecg.modules.wlhy.hybank.entity.HyBank;
import org.jeecg.modules.wlhy.hybank.service.IHyBankService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hydriverbank.entity.HyDriverBank;
import org.jeecg.modules.wlhy.hydriverbank.service.IHyDriverBankService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.utils.DataMaskingUtil;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecg.modules.wlhy.hybank.entity.HyDriverBankDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 司机银行卡信息
 * @Author: duanlikao
 * @Date:   2020-12-14
 * @Version: V1.0
 */
@Api(tags="司机银行卡信息")
@RestController
@RequestMapping("/hydriverbank/hyDriverBank")
@Slf4j
public class HyDriverBankController extends JeecgController<HyDriverBank, IHyDriverBankService> {
	@Autowired
	private IHyDriverBankService hyDriverBankService;

	@Autowired
	private IHyDriverService hyDriverService;

	@Resource
	private IHySettingService settingService;

	@Autowired
	private UserUtil userUtil;

	@Autowired
	private IHyBankService bankService;
	@Autowired
	private IHyCaptainDriverService captainDriverService;
	@Autowired
	private IHyCaptainService captainService;
	@Autowired
	private IHyCaptainVehicleService hyCaptainVehicleService;
	@Autowired
	private IHyDriverVehicleService  driverVehicleService;

	/**
	 * 分页列表查询
	 *
	 * @param hyDriverBank
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="司机银行卡信息-分页列表查询", notes="司机银行卡信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyDriverBankDTO hyDriverBank,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HyDriverBank> queryWrapper = QueryGenerator.initQueryWrapper(hyDriverBank, req.getParameterMap());
		if (userUtil.isCaptain()){
			HashSet<String> driverIdList = new HashSet<>();
			//承运商id获取司机id列表
			List<String> list = captainDriverService.list(new LambdaQueryWrapper<HyCaptainDriver>().eq(HyCaptainDriver::getCaptainId, userUtil.getHyCaptain().getId()).select(HyCaptainDriver::getDriverId)).stream().map(HyCaptainDriver::getDriverId).collect(Collectors.toList());
			if (list.size()!=0){
				driverIdList.addAll(list);
			};
			List<String> list1 = userUtil.getDriverList();
			if (list1.size()!=0){
				driverIdList.addAll(list1);
			}
			//获取的司机数据为承运商添加的司机及承运商所属车辆绑定的司机
			if (driverIdList.size()!=0){
				// queryWrapper.in("d.id",userUtil.getDriverList());
				queryWrapper.in("v.driver_id",driverIdList);
			}else {
				return Result.OK();
			}

		} else if (StringUtils.isNotEmpty(hyDriverBank.getCaptainId())) {
			//根据承运商id获取绑定车辆绑定的司机
			HyCaptain captain = captainService.getById(hyDriverBank.getCaptainId());
			if (captain==null){
				throw new JeecgBootException("未获取到承运商信息");
			}
			HashSet<String> driverIdList = new HashSet<>();
			//承运商id获取司机id列表
			List<String> list = captainDriverService.list(new LambdaQueryWrapper<HyCaptainDriver>().eq(HyCaptainDriver::getCaptainId, hyDriverBank.getCaptainId()).select(HyCaptainDriver::getDriverId)).stream().map(HyCaptainDriver::getDriverId).collect(Collectors.toList());
			if (list.size()!=0){
				driverIdList.addAll(list);
			};

			List<HyCaptainVehicle> carriers = hyCaptainVehicleService.list(new QueryWrapper<HyCaptainVehicle>().eq("captain_id", hyDriverBank.getCaptainId()));
			//根据关联表获取绑定的车辆信息
			List<String> vehicleIdList = carriers.stream().map(HyCaptainVehicle::getVehicleId).collect(Collectors.toList());
			//根据车辆信息获取所绑定的司机信息
			List<String> driverList = new ArrayList<>();
			for (String vehicleId : vehicleIdList) {
				driverList.addAll(driverVehicleService.getDriverIdListByVehicleId(vehicleId));
			}
			//获取的司机数据为承运商添加的司机及承运商所属车辆绑定的司机
			if (driverIdList.size()!=0){
				// queryWrapper.in("d.id",userUtil.getDriverList());
				queryWrapper.in("v.driver_id",driverIdList);
			}else {
				return Result.OK();
			}
		}
		Page<HyDriverBank> page = new Page<HyDriverBank>(pageNo, pageSize);
		IPage<HyDriverBank> pageList = hyDriverBankService.pageList(page, queryWrapper,userUtil.getCustomerById());
//		IPage<HyDriverBank> pageList = hyDriverBankService.page(page, queryWrapper);
		//如果开启系统脱敏
		String dataMaskingFlag = this.settingService.getSettingValueByTag("data_masking");
		if("1".equals(dataMaskingFlag)) {
			for (HyDriverBank dto : pageList.getRecords()) {
				dto.setBankNum(DataMaskingUtil.bankNumberMasking(dto.getBankNum()));
			}
		}

		return Result.OK(pageList);
	}

	@ApiOperation(value="司机银行卡信息-分页列表查询", notes="司机银行卡信息-分页列表查询")
	@GetMapping(value = "/getListByDriverId")
	@ArrayListDict
	public Result<?> getListByDriverId(@RequestParam(name="driverId" , required = true) String driverId) {

		QueryWrapper<HyDriverBank> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("driver_id", driverId)
				.eq("iz_used", "1")
				.eq("del_flag", "0");

		List<HyDriverBank> list = hyDriverBankService.list(queryWrapper);
		return Result.OK(list);
	}

	/**
	 *   添加
	 *
	 * @param hyDriverBank
	 * @return
	 */
	@AutoLog(value = "司机银行卡信息-添加")
	@ApiOperation(value="司机银行卡信息-添加", notes="司机银行卡信息-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("sys:driverBank:add")
	public Result<?> add(@RequestBody HyDriverBank hyDriverBank) {

		//Added at 2023-09-09 for 判断必须绑定本人银行卡
		if ("1".equals(settingService.getSettingValueByTag2("self_bankcard"))) {
			if ("0".equals(hyDriverBank.getSt()) || StringUtils.isNotEmpty(hyDriverBank.getBankName())) {
				return Result.error("当前系统已限定绑定本人银行卡，请联系平台管理员");
			}
		}

		if(StringUtils.isEmpty(hyDriverBank.getBankNum())){
			return Result.error("银行卡号不能为空");
		}

		String driverId = hyDriverBank.getDriverId();
		if(StringUtils.isEmpty(driverId)){
			return Result.error("司机信息不能为空");
		}

		HyDriver hyDriver = hyDriverService.getById(driverId);
		if(hyDriver == null){
			return Result.error("司机信息不存在");
		}

		if("1".equals(hyDriverBank.getSt())){
			hyDriverBank.setBankName(hyDriver.getDriverName());
			hyDriverBank.setIdcard(hyDriver.getIdcard());
		}
		//获取银行行号
		HyBank bank  = bankService.getByBankType(hyDriverBank.getBankType());
		if (bank!=null){
			hyDriverBank.setCrBankNo(bank.getBankHh());
		}else {
			return Result.error("该银行行号信息缺失，请联系管理员进行添加");
		}
		hyDriverBank.setBankNum(hyDriverBank.getBankNum().replaceAll(" ","").trim());
		hyDriverBank.setUserId(hyDriver.getUserId());
		return hyDriverBankService.addDriverBank(hyDriverBank);
	}

	@PostMapping(value = "/setDefaultDriverBank")
	@RequiresPermissions("sys:driverBank:add")
	public Result<?> setDefault(@RequestBody JSONObject jo) {
		String id = jo.getString("id");
		if(StringUtils.isEmpty(id)){
			return Result.error("id不能为空");
		}
		HyDriverBank driverBank = hyDriverBankService.getById(id);
		if(driverBank == null){
			return Result.error("数据不存在");
		}
		return hyDriverBankService.setDefault(driverBank);
	}

	/**
	 *  编辑
	 *
	 * @param hyDriverBank
	 * @return
	 */
	@AutoLog(value = "司机银行卡信息-编辑")
	@ApiOperation(value="司机银行卡信息-编辑", notes="司机银行卡信息-编辑")
	@PutMapping(value = "/edit")
	@RequiresPermissions("sys:driverBank:edit")
	public Result<?> edit(@RequestBody HyDriverBank hyDriverBank) {
		if (StringUtils.isEmpty(hyDriverBank.getBankNum())) {
			return Result.error("银行卡号不能为空");
		}

		if (StringUtils.isEmpty(hyDriverBank.getBankName())) {
			return Result.error("银行卡户名不能为空");
		}

		String id = hyDriverBank.getId();
		if (StringUtils.isEmpty(id)) {
			return Result.error("id不能为空");
		}
		HyDriverBank driverBank = hyDriverBankService.getById(id);
		if (driverBank == null) {
			return Result.error("数据不存在");
		}

		HyDriver hyDriver = hyDriverService.getById(hyDriverBank.getDriverId());
		if (hyDriver == null){
			return Result.error("司机信息不存在");
		}

		//Added at 2023-09-09 for 判断必须绑定本人银行卡
		if ("1".equals(settingService.getSettingValueByTag2("self_bankcard"))) {
			if (!hyDriver.getDriverName().equals(hyDriverBank.getBankName())) {
				return Result.error("当前系统已限定绑定本人银行卡，请联系平台管理员");
			}
		}

		hyDriverBank.setBankNum(hyDriverBank.getBankNum().replaceAll(" ", "").trim());

		if (StringUtils.equals(driverBank.getBankNum(), hyDriverBank.getBankNum()) &&
				StringUtils.equals(driverBank.getBankName(), hyDriverBank.getBankName()) &&
				StringUtils.equals(driverBank.getBankType(), hyDriverBank.getBankType())) {
				hyDriverBankService.updateById(hyDriverBank);
			return Result.OK("修改成功");
		}
		return hyDriverBankService.updateDriverBank(hyDriverBank);
	}

//	/**
//	 *   通过id删除
//	 *
//	 * @param id
//	 * @return
//	 */
//	@AutoLog(value = "司机银行卡信息-通过id删除")
//	@ApiOperation(value="司机银行卡信息-通过id删除", notes="司机银行卡信息-通过id删除")
//	@DeleteMapping(value = "/delete")
//	@RequiresPermissions("sys:driverBank:delete")
//	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
//		hyDriverBankService.removeById(id);
//		return Result.OK("删除成功!");
//	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "司机银行卡信息-批量删除")
//	@ApiOperation(value="司机银行卡信息-批量删除", notes="司机银行卡信息-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	@RequiresPermissions("sys:driverBank:deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		this.hyDriverBankService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="司机银行卡信息-通过id查询", notes="司机银行卡信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyDriverBank hyDriverBank = hyDriverBankService.getById(id);
		if(hyDriverBank==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyDriverBank);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hyDriverBank
    */
    @RequestMapping(value = "/exportXls")
	@RequiresPermissions("sys:driverBank:exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HyDriverBank hyDriverBank) {
        return super.exportXls(request, hyDriverBank, HyDriverBank.class, "司机银行卡信息");
    }

//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//	@RequiresPermissions("sys:driverBank:importExcel")
//	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, HyDriverBank.class);
//    }


	 @ApiOperation(value="司机银行卡信息-通过driverid查询", notes="司机银行卡信息-通过driverid查询")
	 @GetMapping(value = "/getByDriverId")
	 public Result<?> getByDriverId(@RequestParam(name="driverid",required=true) String driverid) {
		 List<HyDriverBank> driverBankList = hyDriverBankService.getByDriverId(driverid);
		 if(driverBankList==null) {
			 return Result.error("未找到对应数据");
		 }
         /*driverBankList.forEach(System.out::println);*/
		 return Result.OK(driverBankList);
	 }









}
